<template>
  <div class="parking-add" >
    <vue-form 
      ref="vueForm"
      :formItem="form_item"
      :fromHandler="form_handler"
      :formData="form_data"
    >
      <template v-slot:city>
        <city-area ref="cityArea" :cityAreaValue.sync="form_data.area" @setMapCenter="setMapCenter" :mapLocation="true" />
      </template>
      <template v-slot:amap >
        <div class="address-map" >
          <a-map @lnglat="lnglat" ref="aMap" @mapLoad="mapLoad" :options="option_map"  />
        </div>
      </template>
    </vue-form>
  </div>
</template>

<script>
import AMap from "../amap"
import CityArea from "@/components/common/cityArea"
import { addParking, ParkingDetailed, ParkingEdit } from "@/api/parking.js"
import VueForm from "@c/form";

export default {
  name: "ParkingAdd",
  components: {
    AMap,
    CityArea,
    VueForm
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if(!value) {
        callback(new Error("----自定义规则"));
      } else {
        callback();
      }
    };
    const validateNumber = (rule, value, callback) => {
      const regNumber = /^[0-9]*$/;
      if(!value) {
        callback(new Error("请输入可停放车辆"));
      } else if(!regNumber.test(value)) {
        callback(new Error("请输入数字"));
      } else {
        callback();
      }
    }
    return {
      form_data: {
        parkingName: "",
        area: "",
        address: "",
        type: "",
        carsNumber: "",
        status: "",
        lnglat: ""
      },
      option_map: {
        mapLoad: true
      },
      id: this.$route.query.id,
      status: this.$store.state.config.radio_disabled,
      type: this.$store.state.config.parking_type,
      form_item: [
        {
          type:"Input",
          label:"停车场名称",
          placeholder:"请输入停车场名称",
          prop:"parkingName",
          width:"200px",
          // validator:[{ validator: validatePass, trigger: 'blur' }], // 表示自定义校验规则
          required:true, // 表示必填项
          requiredMes: "必须要输入", // 表示特别的提示语，默认不写会自带提示语（form组件中）
          rules: [{ min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }] // 表示更多规则
        },
        {type:"Slot",slotName:"city",label:"区域",prop:"area",value:[]},
        {type:"Input",label:"详细地址",placeholder:"请输入详细地址",prop:"address"},
        { 
          type:"Radio",
          label:"类型",
          prop:"type",
          required:true,
          options: this.$store.state.config.parking_type,
        },
        {
          type:"Input",
          label:"可停放车辆",
          placeholder:"请输入车辆",
          prop:"carsNumber",
          validator:[{ validator: validateNumber, trigger: 'blur' }]
        },
        { 
          type:"Radio",
          label:"禁启用",
          prop:"status",
          options: this.$store.state.config.radio_disabled,
        },
        {type:"Slot",slotName:"amap",label:"位置"},
        {type:"Input",label:"经纬度",prop:"lnglat",disabled:true}
      ],
      form_handler: [
        {label: "确定",key:"submit",type:"primary",handler:()=>this.onSubmit()},
        {label: "重置",key:"reset",type:"danger",handler:()=>this.reset()}
      ],
      btnLoading: false,
    } 
  },
  methods: {
    getDetail() {
      if(!this.id) return false;
      ParkingDetailed({id:this.id})
        .then((res) => {
          const data = res.data;
          for(let key in data) {
            if(Object.keys(this.form_data).includes(key)) {
              this.form_data[key] = data[key]
            }
          }
          const splitLnglat = data.lnglat.split(",")
          const lnglat = {
            lng: splitLnglat[0],
            lat: splitLnglat[1]
          }
          this.$refs.aMap.setMarker(lnglat)
          this.$refs.cityArea.initDefault(data.region)
        })
    },
    mapLoad() {
      this.getDetail()
    },
    lnglat(data) {
      this.form_data.lnglat = data.value
    },
    setMapCenter(data) {
      this.$refs.aMap.setMapCenter(data)
    },
    onSubmit() {
      this.$refs.vueForm.$refs.form.validate((valid) => {
        if (valid) {
          this.id ? this.edit() : this.add()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    edit() {
      this.form_data.id = this.id
      this.btnLoading = true
      ParkingEdit(this.form_data)
        .then((res) => {
          this.$message({
            message: res.message,
            type: "success"
          })
          this.btnLoading = false
          this.$router.push({
            name: "ParkingIndex"
          })
        }).catch((err) => this.btnLoading = false)
    },
    add() {
      this.btnLoading = true
      addParking(this.form_data)
        .then((res) => {
          this.$message({
            message: res.message,
            type: "success"
          })
          this.reset("form")
          this.btnLoading = false
        }).catch((err) => this.btnLoading = false)
    },
    reset(formName) {
      this.$refs.vueForm.$refs[formName].resetFields();
      this.$refs.cityArea.clear();
      this.$refs.aMap.clearMarker();
    }
  }
}
</script>

<style lang="scss" scoped>
.address-map {
  width: 100%;
  height: 300px;
}
</style>